﻿using ProcDaemon.Configuration;
using NLog;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Net.Mail;
using System.Net;

namespace ProcDaemon
{
    class Program
    {
        private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
        private static Timer _timer;
        private static int _scanMilliseconds = 1 * 1000;
        private static Daemon _daemon = new Daemon();
        private static int _reScanSeconds = int.Parse(ConfigurationManager.AppSettings["ReScanWaitSecondsAfterException"]);

        static void Main(string[] args)
        {
            Console.Title = "ProcDaemon";

            int seconds = 0;
            if (int.TryParse(ConfigurationManager.AppSettings["ScanSeconds"], out seconds))
            {
                _scanMilliseconds = seconds * 1000;
            }

            //Console.WriteLine("扫描周期: " + (_scanMilliseconds / 1000).ToString() + " 秒");
            //Console.WriteLine("使用q!退出程序");
            //Console.WriteLine();

            ConsoleManager.SetConsole();
            _daemon.Init();

            _timer = new Timer(_timer_Elapsed, null, 0, _scanMilliseconds);

            string line = Console.ReadLine();
            while (line.Trim().ToLower() != "q!")
            {
                line = Console.ReadLine();
            }
        }

        private static void _timer_Elapsed(object state)
        {
            bool isExcepiton = false;
            _timer.Change(Timeout.Infinite, Timeout.Infinite);

            try
            {
                _daemon.Run();
            }
            catch (Exception e)
            {
                isExcepiton = true;
                Console.Write(string.Format("定时器中异常, 详见日志, {0}秒后重新检查", _reScanSeconds));
                _logger.Error("定时器中出现异常: {0}", e.ToString());
            }
            finally
            {
                if (isExcepiton)
                {
                    _timer.Change(_reScanSeconds, _scanMilliseconds);
                }
                else
                {
                    _timer.Change(_scanMilliseconds, _scanMilliseconds);
                }
            }
        }
    }
}

